package com.xxl.job.admin.repository;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.enums.DatabaseTypeEnum;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class XxlJobGroupRepository implements XxlJobGroupDao {

    private final XxlJobGroupDao xxlJobGroupDao;

    public XxlJobGroupRepository(XxlJobGroupDao xxlJobGroupDao) {
        this.xxlJobGroupDao = xxlJobGroupDao;
    }


    @Override
    public List<XxlJobGroup> findAll() {
        return xxlJobGroupDao.findAll();
    }

    @Override
    public List<XxlJobGroup> findByAddressType(int addressType) {
        return xxlJobGroupDao.findByAddressType(addressType);
    }

    @Override
    public int save(XxlJobGroup xxlJobGroup) {
        DatabaseTypeEnum typeEnum = DatabaseTypeEnum.getByType(XxlJobAdminConfig.getAdminConfig().getDatabaseId());
        switch (typeEnum) {
            case MYSQL:
                return xxlJobGroupDao.save(xxlJobGroup);
            case ORACLE:
                // 从Oracle序列中获取ID并设值
                xxlJobGroup.setId(xxlJobGroupDao.getNextOracleSequenceId());
                return xxlJobGroupDao.saveWithId(xxlJobGroup);
            default:
                throw new RuntimeException("un support database type");
        }
    }

    @Override
    public int getNextOracleSequenceId() {
        return xxlJobGroupDao.getNextOracleSequenceId();
    }

    @Override
    public int saveWithId(XxlJobGroup xxlJobGroup) {
        return xxlJobGroupDao.saveWithId(xxlJobGroup);
    }

    @Override
    public int update(XxlJobGroup xxlJobGroup) {
        return xxlJobGroupDao.update(xxlJobGroup);
    }

    @Override
    public int remove(int id) {
        return xxlJobGroupDao.remove(id);
    }

    @Override
    public XxlJobGroup load(int id) {
        return xxlJobGroupDao.load(id);
    }

    @Override
    public List<XxlJobGroup> pageList(int offset, int pagesize, String appname, String title) {
        return xxlJobGroupDao.pageList(offset, pagesize, appname, title);
    }

    @Override
    public int pageListCount(int offset, int pagesize, String appname, String title) {
        return xxlJobGroupDao.pageListCount(offset, pagesize, appname, title);
    }
}
